package com.sky.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.PageDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordEditFailedException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.admin.EmployeeMapper;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        // 采用 MD5 进行加密
        String password = DigestUtils.md5DigestAsHex(
                employeeLoginDTO.getPassword().getBytes()
        );
        //1、根据用户名查询数据库中的数据
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(null != employeeLoginDTO.getUsername(), Employee::getUsername, employeeLoginDTO.getUsername());
        System.out.println("Username = " + employeeLoginDTO.getUsername());
        Employee employee = employeeMapper.selectOne(wrapper);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }


    /**
     * 新增员工
     *
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        // 转换为对应数据库的 entity 对象
        Employee employee = new Employee();
        // 复制属性
        BeanUtils.copyProperties(employeeDTO, employee);
        // 设置默认状态为 1
        employee.setStatus(StatusConstant.ENABLE);
        // 设置默认密码为：123456 采用MD5加密
        String password = DigestUtils.md5DigestAsHex(
                PasswordConstant.DEFAULT_PASSWORD.getBytes()
        );
        employee.setPassword(password);
        // 调用 insert 方法插入到employee表中
        employeeMapper.insert(employee);
    }

    /**
     * 员工分页查询
     *
     * @param name
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public PageDTO<Employee> page(String name, Integer pageNo, Integer pageSize) {
        // 设置分页条件
        Page<Employee> page = Page.of(pageNo, pageSize);
        // 设置查询条件
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(null != name, Employee::getName, name)
                .orderByDesc(Employee::getCreateTime);
        employeeMapper.selectPage(page, wrapper);
        // 提取分页结果
        long total = page.getTotal();
        List<Employee> records = page.getRecords();

        return new PageDTO<>(total, records);
    }

    /**
     * 启用、禁用员工账号
     * @param status
     * @param id
     */
    @Override
    public void updateStatus(Integer status, Long id) {;
        Employee employee = new Employee();
        employee.setStatus(status);
        employee.setId(id);
        employeeMapper.update(employee);
    }

    /**
     * 编辑员工
     * @param employeeDTO
     */
    @Override
    public void updateEmployee(EmployeeDTO employeeDTO) {
        // 转换为 entity 对象
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);

        employeeMapper.update(employee);
    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.selectById(id);
        // 隐藏密码
        employee.setPassword("******");
        return employee;
    }

    /**
     * 修改密码
     * @param passwordEditDTO
     */
    @Override
    public void updatePassword(PasswordEditDTO passwordEditDTO) {
        // 检验原始密码
        String oldStr = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());
        // 查询数据库密码
        Employee employee = employeeMapper.selectById(passwordEditDTO.getEmpId());
        if (StrUtil.isNotBlank(employee.getPassword()) && employee.getPassword().equals(oldStr)) {
            // 修改密码
            String newStr = DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes());
            employee.setPassword(newStr);
            employeeMapper.update(employee);
        } else {
            // 修改失败
            throw new PasswordEditFailedException("原始密码有误");
        }
    }
}
